package application.common.cron4j;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.cron4j.ITask;
import application.common.model.StoreBox;
import application.common.render.HttpClientResult;
import application.common.util.HttpUtil;
import application.common.util.ShiroUtil;
import net.sf.json.JSONObject;

/**
 * 存储同步
 * @author love
 *
 */
public class StoreBoxTask implements ITask{
	
	private boolean isEnd=true;
	public void run() {
		if(isEnd) {
			isEnd=false;
			if(ShiroUtil.getConfig()!=null && !StrKit.isBlank(ShiroUtil.getConfig().getSynURL())) {
				try {
					List<StoreBox> stores=StoreBox.dao.findAll();
					if(stores!=null && stores.size()>0) {
						Map<String, String> params =new HashMap<String,String>();
						params.put("rows", JsonKit.toJson(stores));
						params.put("cabinetId", ShiroUtil.getAuth());
						HttpClientResult httpClientResult=HttpUtil.doPost(String.format("%s/api/cab/store/saveBoxs", ShiroUtil.getConfig().getSynURL()), params);
						if(httpClientResult==null) {
							isEnd=true;
							return;
						}
						if(httpClientResult.getCode()!=200) {
							isEnd=true;
							return;	
						}
						String content=httpClientResult.getContent();
						if(StrKit.isBlank(content)) {
							isEnd=true;
							return;	
						}
						JSONObject jsonObject=JSONObject.fromObject(content);
						if(jsonObject==null) {
							isEnd=true;
							return;	
						}
						if(jsonObject.has("code")) {
							int code=jsonObject.getInt("code");
							if(code!=200) {
								isEnd=true;
								return;	
							}
							isEnd=true;
						}else {
							isEnd=true;
						}
					}else {
						isEnd=true;
					}
				}catch (Exception e) {
					isEnd=true;
				}
			}
			isEnd=true;
		}
	}

	public void stop() {
	}

}
